package com.bdqn.springbootwebsocket.comm;

import com.alibaba.fastjson.JSON;
import com.bdqn.springbootwebsocket.pojo.Message;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
//写一个实现类获取HttpSession
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfigure.class)//代表与前端连接的通道
//用于操作
public class WebSocketServer {

    //用来保存所有在线的人的endpointConfig对象  ConcurrentHashMap是一个线程安全的map集合是map的子类
    public static Map<String, WebSocketServer> onlineUser = new ConcurrentHashMap<>();

    //session专门用来发送websocket消息的 注意是websocket消息不是http消息
    Session session;

    //endpointConfig每当有用户在前端登陆成功并且成功连接到websocket的时候都会生成一个websocket对象


    //会话 HttpSession 当前登录的用户的信息存在HttpSession中
    HttpSession httpSession;

    //用户建立连接触发的方法
    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        this.session = session;
        //通过endpointConfig获取httpSession对象
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().
                get(HttpSession.class.getName());
        //获取存储的用户名
        String user = (String) httpSession.getAttribute("user");
        //将当前登录用户创建的websocket对象存入map集合中
        onlineUser.put(user, this);//key为用户名
        Message message = new Message();
        //是否是全局的系统消息
        message.setSystem(true);
        //给接收者赋值因为是系统消息所以给所有好友发
        message.setReceiver(onlineUser.keySet());
        message.setContent("欢迎" + user + "来到聊天室");
        sendMessage(message);

    }

    public void sendMessage(Message message) {
        try {
            Set<String> receiver = message.getReceiver();
            if (receiver != null) {
                for (String name : receiver) {
                    //通过用户名获取当前websocket对象
                    WebSocketServer webSocketServer = onlineUser.get(name);
                    //通过当前websocket对象的session发送消息
                    webSocketServer.session.getBasicRemote().sendText(JSON.toJSONString(message));
                }
            }else{
                WebSocketServer webSocketServer = onlineUser.get(message.getSender());
                webSocketServer.session.getBasicRemote().sendText(JSON.toJSONString(message));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //测试是否接收到消息
        System.out.println(message);
        //获取从前台获取的消息对象
        //将json字符串转换为对象
        Message message1 = JSON.parseObject(message, Message.class);
        //发送消息
        sendMessage(message1);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {

    }


}
